package cn.jinjimi.app.main.activity;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.InfoUpdateEvent;
import cn.jinjimi.app.controller.event.SiteStatusEvent;
import cn.jinjimi.domain.data.dto.SiteStatusDTO;
import cn.jinjimi.app.entity.Account;
import cn.jinjimi.app.entity.UserProfiles;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.util.NetworkUtils;
import cn.jinjimi.app.util.PhotoUtils;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by m1 on 15/1/22.
 * Modify by Roy on 15/9/1
 */
public class ProfilesActivity extends ToolBarCommonActivity {

    public static final String TAG = ProfilesActivity.class.getSimpleName();
    private ImageView mAvatarImg;

    private TextView mRealNameTv;
    private TextView mMobileTv;
    private TextView mGenderTv;
    private TextView mAreaTv;
    private TextView mCompanyTv;
    private TextView mDescTv;
    private TextView mTagsTv;
    private TextView mHonorTv;
    private TextView mQQTv;
    private TextView mWeChatTv;

    /* 诚信通用户特有的View */
    private RelativeLayout personalPhotoLayout;
    private TextView personalPhotoState;

    /* VIP用户不得修改的View */
    private RelativeLayout areaLayout;
    private RelativeLayout companyLayout;
    private ImageView realNameRightIcon;
    private ImageView areaRightIcon;
    private ImageView companyRightIcon;
    private ImageView ivCompanyRedIcon;

    private SiteStatusDTO siteStatus;

    private final int TypeCheckArea = 0;
    private final int TypeCheckCompany = 1;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_profiles);
        setTitle(getString(R.string.person_info));
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        //我的头像
        mAvatarImg = (ImageView) findViewById(R.id.iv_me);
        areaLayout = (RelativeLayout) findViewById(R.id.rl_area);
        companyLayout = (RelativeLayout) findViewById(R.id.rl_company);
        personalPhotoLayout = (RelativeLayout) findViewById(R.id.rl_personal_photo);

        mRealNameTv = (TextView) findViewById(R.id.real_name);
        mMobileTv = (TextView) findViewById(R.id.mobile);
        mGenderTv = (TextView) findViewById(R.id.sex);
        mAreaTv = (TextView) findViewById(R.id.area);
        mCompanyTv = (TextView) findViewById(R.id.company);
        mDescTv = (TextView) findViewById(R.id.user_desc);
        mTagsTv = (TextView) findViewById(R.id.user_tag);
        mHonorTv = (TextView) findViewById(R.id.user_honor);
        mQQTv = (TextView) findViewById(R.id.user_qq);
        mWeChatTv = (TextView) findViewById(R.id.user_weixin);
        personalPhotoState = (TextView) findViewById(R.id.user_personal_photo_state);

        realNameRightIcon = (ImageView) findViewById(R.id.real_name_icon_right);
        areaRightIcon = (ImageView) findViewById(R.id.area_icon_right);
        companyRightIcon = (ImageView) findViewById(R.id.company_icon_right);
        ivCompanyRedIcon = (ImageView) findViewById(R.id.iv_company_red_icon);
    }

    protected void initListener() {
        findViewById(R.id.rl_pic).setOnClickListener(this);      // 点击头像
        findViewById(R.id.rl_realname).setOnClickListener(this); // 真实姓名
        findViewById(R.id.rl_mobile).setOnClickListener(this);   // 手机号码
        findViewById(R.id.rl_sex).setOnClickListener(this);      // 性别
        areaLayout.setOnClickListener(this);                     // 地区
        companyLayout.setOnClickListener(this);                  // 公司
        findViewById(R.id.rl_desc).setOnClickListener(this);     // 个人简介
        findViewById(R.id.rl_tag).setOnClickListener(this);      // 标签
        findViewById(R.id.rl_honor).setOnClickListener(this);    // 个人荣耀
        findViewById(R.id.rl_qq).setOnClickListener(this);       // QQ号码
        findViewById(R.id.rl_weixin).setOnClickListener(this);   // 微信号
        findViewById(R.id.rl_code).setOnClickListener(this);
        personalPhotoLayout.setOnClickListener(this);
    }

    protected void initData() {
        updateUI();
        showLoadingIndicator();
        UserController.updateUserInfo();
    }

    public void updateUI() {
        Account account = AccountManager.getInstance().getAccount();
        String unSeting = getString(R.string.info_unsetting);
        //加载头像
        mAvatarImg.setImageURI(Uri.parse(AccountManager.getInstance().getAccount().avatar));
        mRealNameTv.setText(account.realName);
        mMobileTv.setText(account.mobile);

        switch (account.gender) {
            case UserProfiles.GENDER_FEMALE:
                mGenderTv.setText(getString(R.string.me_gender_female));
                break;
            case UserProfiles.GENDER_MALE:
                mGenderTv.setText(getString(R.string.me_gender_male));
                break;
            case UserProfiles.GENDER_UNKNOWN:
            default:
                mGenderTv.setText(unSeting);
                break;
        }

        if (TextUtils.isEmpty(account.provinceName) && TextUtils.isEmpty(account.cityName)) {
            mAreaTv.setText(unSeting);
        } else {
            mAreaTv.setText(account.provinceName + " " + account.cityName);
        }
        mTagsTv.setText(TextUtils.isEmpty(account.tags) ? unSeting : account.tags.length() > 10 ? account.tags.substring(0, 10) + "..." : account.tags);
        mQQTv.setText(TextUtils.isEmpty(account.qq) ? unSeting : account.qq);
        mWeChatTv.setText(TextUtils.isEmpty(account.weixin) ? unSeting : account.weixin);
        ivCompanyRedIcon.setVisibility(NoticeManager.hasSetCompany() ? View.INVISIBLE : View.VISIBLE);
        showUserViewByIsVip(account);
    }

    private void showUserViewByIsVip(Account account) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInfoUpdateEvent(InfoUpdateEvent event) {
        hideLoadingIndicator();
        updateUI();
        LogUtil.d(TAG, AccountManager.getInstance().getAccount().toString());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (!NetworkUtils.isNetworkConnected(this)) {
            ToastUtils.toastMessage(this, getString(R.string.networl_useless));
            return;
        }

        Intent intent;
        switch (v.getId()) {
            case R.id.rl_pic:
                PhotoUtils.pickPhoto(ProfilesActivity.this, true);
                break;
            case R.id.rl_realname:
                    ModifyRealNameActivity.launchMeForResult(ProfilesActivity.this, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_mobile:
                break;
            case R.id.rl_sex:
                ModifyGenderActivity.launchMeForResult(ProfilesActivity.this, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_area:
                clickable(false);
                checkAgentStatus(TypeCheckArea);
                break;
            case R.id.rl_company:
                clickable(false);
                checkAgentStatus(TypeCheckCompany);
                break;
            case R.id.rl_desc:
                intent = new Intent(this, PersonalDescActivity.class);
                startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_tag:
                intent = new Intent(this, PersonalTagActivity.class);
                startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_honor:
                intent = new Intent(this, PersonalHonorActivity.class);
                startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_qq:
                intent = new Intent(this, ModifyQQNumActivity.class);
                intent.putExtra(BundleKey.TYPE, ModifyQQNumActivity.TYPE_QQ);
                startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_weixin:
                intent = new Intent(this, ModifyQQNumActivity.class);
                intent.putExtra(BundleKey.TYPE, ModifyQQNumActivity.TYPE_WEIXIN);
                startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_personal_photo:
                intent = new Intent(this, PersonalPhotoActivity.class);
                startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                break;
            case R.id.rl_code:
                mineCode();
                break;
            default:break;

        }
    }

    @EventTrace(EventID.APP_OWNER_CODE)
    public void mineCode() {

    }

    /**
     * 能否再次点击地区和公司信息
     *
     * @param b
     */
    private void clickable(boolean b) {
        areaLayout.setClickable(b);
        companyLayout.setClickable(b);
    }

    private void checkAgentStatus(final int type) {
        ToastUtil.showLoading(this, "");
        UserController.checkAgentStatus(type);
    }

    private boolean canChangeAreaOrCompany() {
        if (siteStatus == null)
            return false;
        return !siteStatus.getIsVip().equals(Constants.IS_VIP);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == QuesCode.QuestCodeModifyInfo) {
            updateUI();
        } else {
            final String path = PhotoUtils.handlePhotoResult(this, data, requestCode, resultCode);
            if (path != null) {

            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSiteStatusEvent(SiteStatusEvent event) {
        if (isFinishing())
            return;

        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                siteStatus = event.data;
                if (event.data != null) {
                    //update account info.
                    AccountManager.getInstance().updateAccount(AccountManager.NameKey.ISVIP, event.data.getIsVip());
                }

                if (canChangeAreaOrCompany()) {
                    if (event.type == 0) {
                        Account account = AccountManager.getInstance().getAccount();
                        Intent intent = new Intent(ProfilesActivity.this, AreaActivity.class);
                        intent.putExtra(BundleKey.PARAM_PROVINCE, account.provinceName);
                        intent.putExtra(BundleKey.PARAM_CITY, account.cityName);
                        startActivityForResult(intent, QuesCode.QuestCodeModifyInfo);
                    } else {
                        SetCompanyActivity.launch(this, SetCompanyActivity.TYPE_UPLOAD_COMPANY);
                    }
                } else {
                    if (event.type == 0) {
                        ToastUtils.toastMessage(ProfilesActivity.this, getString(R.string.vip_no_modify_area));
                    } else {
                        ToastUtils.toastMessage(ProfilesActivity.this, getString(R.string.vip_no_modify_company));
                    }
                }
                clickable(true);
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(ProfilesActivity.this, getString(R.string.loading_user_info_fail));
                clickable(true);
                break;
        }
    }
}
